import axios from 'axios'
import router from '../router'
import { MessageBox, Message } from 'element-ui'
// 测试提交
// create an axios instance
const service = axios.create({
  baseURL: '/api/', // url = base url + request url
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    //if (store.getters.token) {
    config.headers['Authorization'] = 'Bearer ' + window.sessionStorage.getItem('token')
    //}
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const { data, status } = response
    // 请求成功返回data信息
    if (status >= 200 && status < 300) {
      return data
    }


    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  error => {
    let { config, status, data } = error.response
    let message = error.message
    if (status == 401) {
      if (config.url == '/login') {
        message = '用户名或密码输入错误'
      } else {
        router.replace({ name: 'login' })
      }
    }
    if (status == 400) {
      message = Object.values(data)[0][0] || '请求参数错误，请按照要求重新输入'
    }

    Message({
      message,
      type: 'error',
      duration: 5 * 1000
    })
    //return Promise.reject(error)
  }
)

export default service
